package com.jjlin.chapter_3;

import java.util.*;
public class CD176{
    //二叉树节点
    public static class Node{
        public int val;
        public Node left;
        public Node right;
        public Node(int data){
            this.val = data;
        }
    }

    //建立二叉树
    public static HashMap<Integer, Node> creatNodeList(int[][] nums){
        HashMap<Integer, Node> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            map.putIfAbsent(nums[i][0], new Node(nums[i][0]));
            if(nums[i][1] != 0){
                map.putIfAbsent(nums[i][1], new Node(nums[i][1]));
                map.get(nums[i][0]).left = map.get(nums[i][1]);
            }
            if(nums[i][2] != 0){
                map.putIfAbsent(nums[i][2], new Node(nums[i][2]));
                map.get(nums[i][0]).right = map.get(nums[i][2]);
            }
        }
        return map;
    }

    //在二叉树中找到两个节点的最近公共祖先
    public static Node lowestAncestor(Node head, Node o1, Node o2){
        if(head == null || head == o1 || head == o2)
            return head;
        Node left = lowestAncestor(head.left, o1, o2);
        Node right = lowestAncestor(head.right, o1, o2);
        if(left != null && right != null)
            return head;
        return left != null ? left : right;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int root = sc.nextInt();
        int[][] nums = new int[n][3];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < 3; j++)
                nums[i][j] = sc.nextInt();
        int o1 = sc.nextInt();
        int o2 = sc.nextInt();
        HashMap<Integer, Node> map = creatNodeList(nums);
        Node head = map.get(root);
        Node node1 = map.get(o1);
        Node node2 = map.get(o2);
        Node res = lowestAncestor(head, node1, node2);
        if(res != null)
            System.out.println(res.val);
    }
}